// components/SingerList/SingerList.js
Component({
  properties: {
    data: {
      type: Array,
      value: []
    },
    scrollTop: {
      type: Number,
      value: 0
    }
  },
  data: {
    defaultId: '热',
    curIndex: 0,
    listHeights: [],
    groupRef: []
  },
  pageLifetimes: {
    show() {
      const groupRef = wx.createSelectorQuery().in(this)
      groupRef.selectAll('.group').boundingClientRect(rect => {
        const listHeights = rect.map(item => item.top)
        this.setData({
          listHeights,
          groupRef: rect
        })
      }).exec()
    }
  },
  observers: {
    data() {
      console.log(12)
      this.calculate() 
    },
    scrollTop(newVal) {
      const singersVal = this.data.listHeights
      // 在最开始的时候push了一个0，这里就需要-1，相对应
      for (let i = 0; i < singersVal.length - 1; i++) {
        const heightTop = singersVal[i]
        const heightBottom = singersVal[i + 1]
        if (newVal >= heightTop && newVal <= heightBottom) {
          this.setData({
            curIndex: i
          })
        }
      }
    }
  },
  methods: {
    onScrollTo({currentTarget: {dataset}}) {
      const {id, index} = dataset
      const query = wx.createSelectorQuery().in(this)
      query.select(`#${dataset.id}`).boundingClientRect(rect => {
        this.setData({curIndex: index})
        this.triggerEvent('scrollY', {
          scrollTop: rect.top,
          alphaId: id
        })
      }).exec()
    },
    // 计算每一项列表的高度区间
    calculate() {
      const {listHeights, groupRef} = this.data
      // 区间高度
      let height = 0
      // 每次计算前都要先清空,从0开始
      listHeights.length = 0
      listHeights.push(height)
      for (let i = 0; i < groupRef.length; i++) {
        height += groupRef[i].height
        listHeights.push(height)
      }
      this.setData({listHeights})
    }
  }
})
